"""
模块类型：xxx.py
    1.内置模块：自带模块
    2.自定义模块：包package
    3.三方模块：pip install xxxx
pymysql模块
    连接MySQL数据库：执行增删改查操作
安装pymysql模块
    1、pip install pymqsl
    2、python环境中导入pymql
流程：
    1、创建数据库连接
    2、基于连接创建游标，游标作用：执行SQL语句，接收返回结果
    3、执行SQL语句，且满足事务条件
    4、关闭游标、数据连接
"""
import pymysql

# 查询数据
def selectData():
    dbconn = pymysql.connect(host="192.168.189.141", user="admin", password="admin", database="testdb")
    # 建立游标
    cr = dbconn.cursor()

    test_sql = "select * from serverhost"
    # 显示受影响行数
    result = cr.execute(test_sql)
    print("行数: ", result)

    print("----------" * 8)

    # 获取数据,元组套元组，一个小元组，对应一行信息
    data_01 = cr.fetchall()
    mysql_data(data_01)

    cr.close()
    dbconn.close()

# 写操作
def writeData():
    dbconn = pymysql.connect(host="192.168.189.141",user="admin",password="admin",database="testdb")
    cr = dbconn.cursor()

    insert_mysql = "insert into serverhost(ip,username,password,port) values('192.168.189.142','root','123456',22)"
    update_mysql = "update serverhost set ip='192.168.189.140' where ip='10.1.1.1'"
    insert_result = cr.execute(insert_mysql)
    print("插入行数：",insert_result)
    insert_data = cr.fetchall()
    mysql_data(insert_data)

    update_result = cr.execute(update_mysql)
    print("更新行数：",update_result)
    update_data = cr.fetchall()
    mysql_data(update_data)

    dbconn.commit()

    cr.close()
    dbconn.close()

def mysql_data(mysqldata):
    for i in range(0,len(mysqldata)):
        info = mysqldata[i]
        print("ip:%s,username:%s,password:%s,port:%d" % (info[0],info[1],info[2],info[3]))
        print("----------"*8)

if __name__ == '__main__':

    selectData()